﻿#ifndef __WorkQueue_H__
#define __WorkQueue_H__

#include "kernel/ref_ptr.h"
#include "kernel/ogrestringvector.h"
#include "kernel/OgreException.h"
#include "kernel/threading/threaddefines.h"
#include "kernel/Referenced.h"
#include "kernel/OgreAny.h"

namespace FD
{
	namespace Kernel
	{
		/** Interface to a general purpose request / response style background work queue.
		@remarks
		A work queue is a simple structure, where requests for work are placed
		onto the queue, then removed by a worker for processing, then finally
		a response is placed on the result queue for the originator to pick up
		at their leisure. The typical use for this is in a threaded environment,
		although any kind of deferred processing could use this approach to
		decouple and distribute work over a period of time even
		if it was single threaded.
		@par
		WorkQueues also incorporate thread pools. One or more background worker threads
		can wait on the queue and be notified when a request is waiting to be
		processed. For maximal thread usage, a FD::Kernel::WorkQueue instance should be shared
		among many sources of work, rather than many work queues being created.
		This way, you can share a small number of hardware threads among a large
		number of background tasks. This doesn't mean you have to implement all the
		request processing in one class, you can plug in many handlers in order to
		process the requests.
		@par
		This is an abstract interface definition; users can subclass this and
		provide their own implementation if required to centralise task management
		in their own subsystems. We also provide a default implementation in the
		form of CDefaultWorkQueue.
		*/

		enum WorkQueuePriority
		{
			Work_Queue_Tile    = 100,
			Work_Queue_Vector  = 200,
			Work_Queue_Model   = 300,
			Work_Queue_Effect  = 400,
			Work_Queue_Kml     = 500,
			Work_Queue_Default = 600,
			Work_Queue_Custom  = 1000
		};  

		class FD_Kernel_Export WorkQueueChannelListener : public FD::Kernel::CReferenced
		{
		public:
			WorkQueueChannelListener(){}
			~WorkQueueChannelListener(){}
		public:
			//
			virtual bool preRequestSorted(UINT16 channelID){return false;}
			virtual void postRequestSorted(UINT16 channelID){}
		};

		class FD_Kernel_Export WorkQueue : public FD::Kernel::CReferenced
		{
		public:
			class CRequest;
			class CResponse;
		protected:
			typedef std::pair<uint32,FD::Kernel::WorkQueueChannelListener*> PriorityListenerPair;
			typedef map<UINT16,PriorityListenerPair> ChannelMap;
			typedef map<String, uint16> ChannelMap1;
			ChannelMap1 mChannelMap1;
			ChannelMap mChannelMap;
			UINT16 mNextChannel;
			OGRE_MUTEX(mChannelMapMutex);

			typedef std::vector<CRequest*> RequestVec;
			RequestVec mTmpRequest;

			typedef std::vector<CResponse*> ResponseVec;
			ResponseVec mTmpResponse;
		public:
			
			class FD_Kernel_Export RequestPara : public FD::Kernel::CReferenced
			{
			public:
				RequestPara(): mParent(NULL){}
				virtual ~RequestPara(){}                

			public:
				virtual FD::Kernel::WorkQueue::RequestPara& operator=(const FD::Kernel::WorkQueue::RequestPara& rhs){ this->mParent = rhs.mParent;return *this;}
				virtual bool operator<(const FD::Kernel::WorkQueue::RequestPara& rhs) const;

			public:
				virtual FD::Kernel::WorkQueue::RequestPara* clone()const 
				{
					FD_EXCEPT(Exception::ERR_NOT_IMPLEMENTED
						,"The method is not implemented"
						,"FD::Kernel::WorkQueue::RequestPara::clone");
					return NULL;
				}
				FD::Kernel::WorkQueue::CRequest* getRequest()const{return mParent;}
				void setRequest(FD::Kernel::WorkQueue::CRequest* parent)const {mParent = parent;}
			private:
				mutable FD::Kernel::WorkQueue::CRequest* mParent;
			};

			class FD_Kernel_Export ResponsePara : public FD::Kernel::CReferenced
			{
			public:
				ResponsePara(): mParent(NULL){}
				virtual ~ResponsePara(){}

			public:
				virtual FD::Kernel::WorkQueue::ResponsePara& operator=(const FD::Kernel::WorkQueue::ResponsePara& rhs){ this->mParent = rhs.mParent;return *this;}
			public:
				virtual  FD::Kernel::WorkQueue::ResponsePara* clone()const 
				{
					FD_EXCEPT(Exception::ERR_NOT_IMPLEMENTED
						,"The method is not implemented"
						,"FD::Kernel::WorkQueue::ResponsePara::clone");
					return NULL;
				}
				FD::Kernel::WorkQueue::CResponse* getResponse()const{return mParent;}
				void setResponse(FD::Kernel::WorkQueue::CResponse* parent)const {mParent = parent;}
			private:
				mutable FD::Kernel::WorkQueue::CResponse* mParent;
			};

			//// Numeric identifier for a request
			typedef unsigned long long int RequestID;
			/** General purpose request structure.
			*/
			class FD_Kernel_Export CRequest : public FD::Kernel::CReferenced
			{
				friend class WorkQueue;                    
			protected:
				//// The request channel, as an integer
				UINT16 mChannel;                    
				//// The request type, as an integer within the channel (user can define enumerations on this)
				UINT16 mType;
				//// The details of the request (user defined)
				FD::Kernel::WorkQueue::RequestPara* mData;
				/// The details of the request (user defined)
				Any mAnyData;
				//// Retry count - set this to non-zero to have the request try again on failure
				UINT8 mRetryCount;
				//// Identifier (assigned by the system)
				RequestID mID;
				//// Abort Flag
				mutable bool mAborted;

				UINT64 mFilter;

			public:
				//// Constructor
				CRequest(UINT16 channel, UINT16 rtype, const FD::Kernel::WorkQueue::RequestPara &rData, UINT8 retry, RequestID rid);                  
				CRequest(UINT16 channel, UINT16 rtype, const FD::Kernel::WorkQueue::RequestPara &rData, UINT8 retry, RequestID rid,UINT64 filter);
				/// Constructor 
				CRequest(uint16 channel, uint16 rtype, const Any& rData, uint8 retry, RequestID rid);

				virtual ~CRequest();
			public: 
				//// Set the abort flag
				void abortRequest() const;
				//// Get the request channel (top level categorisation)
				UINT16 getChannel() const;
				//// Get the type of this request within the given channel
				UINT16 getType() const;
				//// Get the user details of this request
				const FD::Kernel::WorkQueue::RequestPara& getData() const;
				/// Get the user details of this request
				const Any& getAnyData() const { return mAnyData; }
				//// Get the remaining retry count
				UINT8 getRetryCount() const;
				//// Get the identifier of this request
				RequestID getID() const;
				//// Get the abort flag
				bool getAborted() const;

				UINT64 getFilter()const;
			};
			/** General purpose response structure.
			*/
			class FD_Kernel_Export CResponse : public FD::Kernel::CReferenced
			{
			private:
				//// Pointer to the request that this response is in relation to
				const FD::Kernel::WorkQueue::CRequest *mRequest;
				//// Whether the work item succeeded or not
				bool mSuccess;
				//// CAny diagnostic messages
				String mMessages;
				//// Data associated with the result of the process                
				FD::Kernel::WorkQueue::ResponsePara* mData;
				Any mAnyData;

			public:
				CResponse(const FD::Kernel::WorkQueue::CRequest *rq, bool success, const FD::Kernel::WorkQueue::ResponsePara &data, const String &msg);
				CResponse(const FD::Kernel::WorkQueue::CRequest *rq, bool success, const FD::Kernel::WorkQueue::ResponsePara &data);
				CResponse(const CRequest* rq, bool success, const Any& data, const String& msg = "");
			public:

				virtual ~CResponse();
				//// Get the request that this is a response to (NB destruction destroys this)
				const FD::Kernel::WorkQueue::CRequest *getRequest() const;
				//// Return whether this is a successful response
				bool succeeded() const;
				//// Get any diagnostic messages about the process
				const String &getMessages() const;
				//// Abort the request
				void abortRequest();                
				//// Return the response data (user defined, only valid on success)
				const FD::Kernel::WorkQueue::ResponsePara &getData() const;

				/// Return the response data (user defined, only valid on success)
				const Any& getAnyData() const { return mAnyData; }
			};
			/** Interface definition for a handler of requests.
			@remarks
			User classes are expected to implement this interface in order to
			process requests on the queue. It's important to realise that
			the calls to this class may be in a separate thread to the main
			render context, and as such it may not be possible to make
			rendersystem or other GPU-dependent calls in this handler. You can only
			do so if the queue was created with 'workersCanAccessRenderSystem'
			set to true, and OGRE_THREAD_SUPPORT=1, but this puts extra strain
			on the thread safety of the render system and is not recommended.
			It is best to perform CPU-side work in these handlers and let the
			response handler transfer results to the GPU in the main render thread.
			*/
			class FD_Kernel_Export CRequestHandler /*: public FD::Kernel::CReferenced*/
			{
			public:
				CRequestHandler();
				virtual ~CRequestHandler();
				/** Return whether this handler can process a given request.
				@remarks
				Defaults to true, but if you wish to add several handlers each of
				which deal with different types of request, you can override
				this method.
				*/
				virtual bool canHandleRequest(const FD::Kernel::WorkQueue::CRequest *req, const WorkQueue *srcQ);
				/** The handler method every subclass must implement.
				If a failure is encountered, return a Response with a failure
				result rather than raise an exception.
				@param req The CRequest structure, which is effectively owned by the
				handler during this call. It must be attached to the returned
				Response regardless of success or failure.
				@param srcQ The work queue that this request originated from
				@return Pointer to a Response object - the caller is responsible
				for deleting the object.
				*/
				virtual FD::Kernel::WorkQueue::CResponse *handleRequest(const FD::Kernel::WorkQueue::CRequest *req, const WorkQueue *srcQ);
			};
			/** Interface definition for a handler of responses.
			@remarks
			User classes are expected to implement this interface in order to
			process responses from the queue. All calls to this class will be
			in the main render thread and thus all GPU resources will be
			available.
			*/
			class FD_Kernel_Export CResponseHandler : public FD::Kernel::CReferenced
			{
			public:
				CResponseHandler();
				virtual ~CResponseHandler();
				/** Return whether this handler can process a given response.
				@remarks
				Defaults to true, but if you wish to add several handlers each of
				which deal with different types of response, you can override
				this method.
				*/
				virtual bool canHandleResponse(const FD::Kernel::WorkQueue::CResponse *res, const WorkQueue *srcQ);
				/** The handler method every subclass must implement.
				@param res The Response structure. The caller is responsible for
				deleting this after the call is made, none of the data contained
				(except pointers to structures in user CAny data) will persist
				after this call is returned.
				@param srcQ The work queue that this request originated from
				*/
				virtual void handleResponse(const FD::Kernel::WorkQueue::CResponse *res, const WorkQueue *srcQ);
			};
			WorkQueue();
			virtual ~WorkQueue();
		public:
			/** Start up the queue with the options that have been set.
			@param forceRestart If the queue is already running, whether to shut it
			down and restart.
			*/
			/*virtual void startup(bool forceRestart = true);*/
			virtual void startup(bool forceRestart);
			virtual void startup();
			/** Add a request handler instance to the queue.
			@remarks
			Every queue must have at least one request handler instance for each
			channel in which requests are raised. If you
			add more than one handler per channel, then you must implement canHandleRequest
			differently	in each if you wish them to respond to different requests.
			@param channel The channel for requests you want to handle
			@param rh Your handler
			*/
			virtual void addRequestHandler(UINT16 channel, FD::Kernel::WorkQueue::CRequestHandler *rh);
			/** Remove a request handler. */
			virtual void removeRequestHandler(UINT16 channel, FD::Kernel::WorkQueue::CRequestHandler *rh);
			/** Add a response handler instance to the queue.
			@remarks
			Every queue must have at least one response handler instance for each
			channel in which requests are raised. If you add more than one, then you
			must implement canHandleResponse differently in each if you wish them
			to respond to different responses.
			@param channel The channel for responses you want to handle
			@param rh Your handler
			*/
			virtual void addResponseHandler(UINT16 channel, FD::Kernel::WorkQueue::CResponseHandler *rh);
			/** Remove a Response handler. */
			virtual void removeResponseHandler(UINT16 channel, FD::Kernel::WorkQueue::CResponseHandler *rh);

			/** Add a new request to the queue.
			@param channel The channel this request will go into = 0; the channel is the top-level
			categorisation of the request
			@param requestType An identifier that's unique within this queue which
			identifies the type of the request (user decides the actual value)
			@param rData The data required by the request process.
			@param retryCount The number of times the request should be retried
			if it fails.
			@param forceSynchronous Forces the request to be processed immediately
			even if threading is enabled.
			@returns The ID of the request that has been added
			*//*
			virtual RequestID addRequest(UINT16 channel, UINT16 requestType, const CAny& rData,
			UINT8 retryCount = 0, bool forceSynchronous = false);*/
			virtual RequestID addRequest(UINT16 channel, UINT16 requestType, const FD::Kernel::WorkQueue::RequestPara &rData, UINT8 retryCount, bool forceSynchronous,UINT64 filter);
			virtual RequestID addRequest(UINT16 channel, UINT16 requestType, const FD::Kernel::WorkQueue::RequestPara &rData, UINT8 retryCount, bool forceSynchronous);
			virtual RequestID addRequest(UINT16 channel, UINT16 requestType, const FD::Kernel::WorkQueue::RequestPara &rData, UINT8 retryCount);
			virtual RequestID addRequest(UINT16 channel, UINT16 requestType, const FD::Kernel::WorkQueue::RequestPara &rData);

			/** Add a new request to the queue.
			@param channel The channel this request will go into = 0; the channel is the top-level
			categorisation of the request
			@param requestType An identifier that's unique within this queue which
			identifies the type of the request (user decides the actual value)
			@param rData The data required by the request process. 
			@param retryCount The number of times the request should be retried
			if it fails.
			@param forceSynchronous Forces the request to be processed immediately
			even if threading is enabled.
			@param idleThread Request should be processed on the idle thread.
			Idle requests will be processed on a single worker thread. You should use this in the following situations:
			1. If a request handler can't process multiple requests in parallel.
			2. If you add lot of requests, but you want to keep the game fast.
			3. If you have lot of more important threads. (example: physics).
			@return The ID of the request that has been added
			*/
			virtual RequestID addRequest(uint16 channel, uint16 requestType, const Any& rData, uint8 retryCount = 0, 
				bool forceSynchronous = false, bool idleThread = false) = 0;

			virtual RequestID addOrReplaceRequest(UINT16 channel, UINT16 requestType, const FD::Kernel::WorkQueue::RequestPara &rData, UINT8 retryCount, bool forceSynchronous, UINT64 filter);
		public:
			/** Abort a previously issued request.
			If the request is still waiting to be processed, it will be
			removed from the queue.
			@param id The ID of the previously issued request.
			*/
			virtual void abortRequest(RequestID id);
			/** Abort all previously issued requests in a given channel.
			CAny requests still waiting to be processed of the given channel, will be
			removed from the queue.
			@param channel The type of request to be aborted
			*/
			virtual void abortRequestsByChannel(UINT16 channel);
			virtual void abortRequestsByFilter(UINT16 channel,UINT64 filter);
			/** Abort all previously issued requests.
			CAny requests still waiting to be processed will be removed from the queue.
			CAny requests that are being processed will still complete.
			*/
			virtual void abortAllRequests();

			/** Set whether to pause further processing of any requests.
			If true, any further requests will simply be queued and not processed until
			setPaused(false) is called. CAny requests which are in the process of being
			worked on already will still continue.
			*/
			virtual void setPaused(bool pause);
			//// Return whether the queue is paused ie not sending more work to workers
			virtual bool isPaused() const;
			/** Set whether to accept new requests or not.
			If true, requests are added to the queue as usual. If false, requests
			are silently ignored until setRequestsAccepted(true) is called.
			*/
			virtual void setRequestsAccepted(bool accept);
			//// Returns whether requests are being accepted right now
			virtual bool getRequestsAccepted() const;
			/** Process the responses in the queue.
			@remarks
			This method is public, and must be called from the main render
			thread to 'pump' responses through the system. The method will usually
			try to clear all responses before returning = 0; however, you can specify
			a time limit on the response processing to limit the impact of
			spikes in demand by calling setResponseProcessingTimeLimit.
			*/
			virtual void processResponses();
			/** Get the time limit imposed on the processing of responses in a
			single frame, in milliseconds (0 indicates no limit).
			*/
			virtual uint32 getResponseProcessingTimeLimit() const;
			/** Set the time limit imposed on the processing of responses in a
			single frame, in milliseconds (0 indicates no limit).
			This sets the maximum time that will be spent in processResponses() in
			a single frame. The default is 8ms.
			*/
			virtual void setResponseProcessingTimeLimit(uint32 ms);
			/** Shut down the queue.
			*/
			virtual void shutdown();
			/** Get a channel ID for a given channel priority.
			@remarks
			Channels are assigned on a first-come, first-served basis and are
			not persistent across application instances. This method allows
			applications to not worry about channel clashes through manually
			assigned channel numbers.
			*/
			virtual UINT16 getChannel(uint32 priority = Work_Queue_Default);

			/** Get a channel ID for a given channel name. 
			@remarks
			Channels are assigned on a first-come, first-served basis and are
			not persistent across application instances. This method allows 
			applications to not worry about channel clashes through manually
			assigned channel numbers.
			*/
			virtual uint16 getChannel(const String& channelName);

			virtual bool setChannelListener(UINT16 channelID,FD::Kernel::WorkQueueChannelListener* pListener);
			virtual FD::Kernel::WorkQueueChannelListener* getChannelListener(UINT16 channelID)const;
		};
		/** Base for a general purpose request / response style background work queue.
		*/
		class FD_Kernel_Export DefaultWorkQueueBase : public FD::Kernel::WorkQueue
		{
			/**
			*  在_Graphic里面的时候掉用了CRoot::getSingleton().getRenderSystem()->func()，
			*  移植到Core后，不能使用这些函数，但这些函数是用来确保OpenGl渲染系统在多线程下能正常工作的，
			*  所以采用注册回调函数的方式，在三维里使用注册回调(已经在_Graphic里实现)，如不使用，直接
			*  取消注册即可。
			*/
		protected:
			typedef void (*pfpreExtraThreadsStartedFunc)();
			typedef void (*pfpostExtraThreadsStartedFunc)();
			typedef void (*pfregisterThreadFunc)();
			typedef void (*pfunregisterThreadFunc)();
			typedef void (*pfflushRenderSystemFunc)();
			pfpreExtraThreadsStartedFunc   mppreExtraThreadsStartedCallBack;
			pfpostExtraThreadsStartedFunc  mppostExtraThreadsStartedsCallBack;
			pfregisterThreadFunc           mpregisterThreadCallBack;
			pfunregisterThreadFunc			mpunregisterThreadCallBack;
			pfflushRenderSystemFunc           mpflushRenderSystemCallBack;

		public:
			void registerPreExtraThreadsStartedFunc(void *preExtraThreadsStartedFunc);
			void registerPostExtraThreadsStartedFunc(void *postExtraThreadsStartedFunc);
			void registerThreadFunc (void *pThreadFunc);
			void registerThreadFunc2 (void *pThreadFunc);
			void registerflushRenderSystemFunc (void *pflushRenderSystemFunc);
			void unregisterPreExtraThreadsStartedFunc();
			void unregisterPostExtraThreadsStartedFunc();
			void unregisterThreadFunc();
			void unregisterThreadFunc2();
			void unregisterflushRenderSystemFunc();

		public:
			/** Constructor.
			Call startup() to initialise.
			@param name Optional name, just helps to identify logging output
			*/
			DefaultWorkQueueBase(const String &name);
			DefaultWorkQueueBase();
			virtual ~DefaultWorkQueueBase();
			//// Get the name of the work queue
			const String &getName() const;
			/** Get the number of worker threads that this queue will start when
			startup() is called.
			*/
			virtual size_t getWorkerThreadCount() const;
			/** Set the number of worker threads that this queue will start
			when startup() is called (default 1).
			Calling this will have no effect unless the queue is shut down and
			restarted.
			*/
			virtual void setWorkerThreadCount(size_t c);
			/** Get whether worker threads will be allowed to access render system
			resources.
			Accessing render system resources from a separate thread can require that
			a context is maintained for that thread. Also, it requires that the
			render system is running in threadsafe mode, which only happens
			when OGRE_THREAD_SUPPORT=1. This option defaults to false, which means
			that threads can not use GPU resources, and the render system can
			work in non-threadsafe mode, which is more efficient.
			*/
			virtual bool getWorkersCanAccessRenderSystem() const;

			/** Set whether worker threads will be allowed to access render system
			resources.
			Accessing render system resources from a separate thread can require that
			a context is maintained for that thread. Also, it requires that the
			render system is running in threadsafe mode, which only happens
			when OGRE_THREAD_SUPPORT=1. This option defaults to false, which means
			that threads can not use GPU resources, and the render system can
			work in non-threadsafe mode, which is more efficient.
			Calling this will have no effect unless the queue is shut down and
			restarted.
			*/
			virtual void setWorkersCanAccessRenderSystem(bool access);
			/** Process the next request on the queue.
			@remarks
			This method is public, but only intended for advanced users to call.
			own thread to drive the worker processing. The thread calling this
			method will be the thread used to call the FD::Kernel::WorkQueue::CRequestHandler.
			*/
			virtual void _processNextRequest();
			//// Main function for each thread spawned.
			virtual void _threadMain();
			/** Returns whether the queue is trying to shut down. */
			virtual bool isShuttingDown() const;
			//// @copydoc WorkQueue::addRequestHandler
			virtual void addRequestHandler(UINT16 channel, FD::Kernel::WorkQueue::CRequestHandler *rh);
			//// @copydoc WorkQueue::removeRequestHandler
			virtual void removeRequestHandler(UINT16 channel, FD::Kernel::WorkQueue::CRequestHandler *rh);
			//// @copydoc WorkQueue::addResponseHandler
			virtual void addResponseHandler(UINT16 channel, FD::Kernel::WorkQueue::CResponseHandler *rh);
			//// @copydoc WorkQueue::removeResponseHandler
			virtual void removeResponseHandler(UINT16 channel, FD::Kernel::WorkQueue::CResponseHandler *rh);

			//// @copydoc WorkQueue::addRequest
			///virtual RequestID addRequest(UINT16 channel, UINT16 requestType, const CAny& rData, UINT8 retryCount = 0,
			///	bool forceSynchronous = false);
			virtual RequestID addRequest(UINT16 channel, UINT16 requestType, const FD::Kernel::WorkQueue::RequestPara &rData, UINT8 retryCount, bool forceSynchronous, UINT64 filter);

			virtual RequestID addRequest(uint16 channel, uint16 requestType, const Any& rData, uint8 retryCount = 0, 
				bool forceSynchronous = false, bool idleThread = false);

			virtual RequestID addOrReplaceRequest(UINT16 channel, UINT16 requestType, const FD::Kernel::WorkQueue::RequestPara &rData, UINT8 retryCount, bool forceSynchronous, UINT64 filter);
		public:
			//// @copydoc WorkQueue::abortRequest
			virtual void abortRequest(RequestID id);
			//// @copydoc WorkQueue::abortRequestsByChannel
			virtual void abortRequestsByChannel(UINT16 channel);
			virtual void abortRequestsByFilter(UINT16 channel,UINT64 filter);
			//// @copydoc WorkQueue::abortAllRequests
			virtual void abortAllRequests();
			//// @copydoc WorkQueue::setPaused
			virtual void setPaused(bool pause);
			//// @copydoc WorkQueue::isPaused
			virtual bool isPaused() const;
			//// @copydoc WorkQueue::setRequestsAccepted
			virtual void setRequestsAccepted(bool accept);
			//// @copydoc WorkQueue::getRequestsAccepted
			virtual bool getRequestsAccepted() const;
			//// @copydoc WorkQueue::processResponses
			virtual void processResponses();
			//// @copydoc WorkQueue::getResponseProcessingTimeLimit
			virtual uint32 getResponseProcessingTimeLimit() const;
			//// @copydoc WorkQueue::setResponseProcessingTimeLimit
			virtual void setResponseProcessingTimeLimit(uint32 ms);
		protected:
			String mName;
			size_t mWorkerThreadCount;
			bool mWorkerRenderSystemAccess;
			bool mIsRunning;
			uint32 mResposeTimeLimitMS;

			typedef deque<FD::Kernel::WorkQueue::CRequest *> RequestQueue;
			typedef deque<FD::Kernel::WorkQueue::CResponse *> ResponseQueue;
			typedef map<uint32,RequestQueue> RequestQueueMap;
			typedef map<uint32,ResponseQueue> ResponseQueueMap;
			RequestQueueMap mRequestQueueMap;
			RequestQueue mProcessQueue;
			ResponseQueueMap mResponseQueueMap;

			typedef std::deque<CRequest*> RequestQueue;
			typedef std::deque<CResponse*> ResponseQueue;
			RequestQueue mRequestQueue; // Guarded by mRequestMutex
			//RequestQueue mProcessQueue; // Guarded by mProcessMutex
			ResponseQueue mResponseQueue; // Guarded by mResponseMutex

			//// Thread function
			struct WorkerFunc OGRE_THREAD_WORKER_INHERIT
			{
				DefaultWorkQueueBase *mQueue;
				WorkerFunc(DefaultWorkQueueBase *q)
					: mQueue(q) {}
				void run();
			};

			WorkerFunc *mWorkerFunc;
			/** Intermediate structure to hold a pointer to a request handler which
			provides insurance against the handler itself being disconnected
			while the list remains unchanged.
			*/
		public:
			class FD_Kernel_Export CRequestHandlerHolder : public FD::Kernel::CReferenced
			{
			protected:
				OGRE_RW_MUTEX(mRWMutex);
				FD::Kernel::WorkQueue::CRequestHandler *mHandler;

			public:
				CRequestHandlerHolder(CRequestHandler *handler);
				/// Disconnect the handler to allow it to be destroyed
				void disconnectHandler();
				/** Get handler pointer - note, only use this for == comparison or similar,
				do not attempt to call it as it is not thread safe.
				*/
				FD::Kernel::WorkQueue::CRequestHandler *getHandler();
				/** Process a request if possible.
				@return Valid response if processed, null otherwise
				*/
				FD::Kernel::WorkQueue::CResponse *handleRequest(const FD::Kernel::WorkQueue::CRequest *req, const WorkQueue *srcQ);
			};
		protected:

			/// Hold these by shared pointer so they can be copied keeping same instance
			typedef FD::Kernel::ref_ptr<CRequestHandlerHolder> RequestHandlerHolderPtr;
			typedef list<RequestHandlerHolderPtr> RequestHandlerList;
			typedef list<FD::Kernel::WorkQueue::CResponseHandler *> ResponseHandlerList;
			typedef map<UINT16, RequestHandlerList> RequestHandlerListByChannel;
			typedef map<UINT16, ResponseHandlerList> ResponseHandlerListByChannel;
			RequestHandlerListByChannel mRequestHandlers;
			ResponseHandlerListByChannel mResponseHandlers;
			RequestID mRequestCount;
			bool mPaused;
			bool mAcceptRequests;
			bool mShuttingDown;
			OGRE_MUTEX(mRequestMutex);
			OGRE_MUTEX(mProcessMutex);
			OGRE_MUTEX(mResponseMutex);
			OGRE_RW_MUTEX(mRequestHandlerMutex);

			FD::Kernel::WorkQueue::CRequest* takeoutRequest(RequestQueue& queue);

			void processRequestResponse(FD::Kernel::WorkQueue::CRequest *r, bool synchronous);
			FD::Kernel::WorkQueue::CResponse *processRequest(FD::Kernel::WorkQueue::CRequest *r);
			void processResponse(FD::Kernel::WorkQueue::CResponse *r);
			//// Put a FD::Kernel::WorkQueue::CRequest on the queue with a specific RequestID.
			void addRequestWithRID(RequestID rid, UINT16 channel, UINT16 requestType, const FD::Kernel::WorkQueue::RequestPara &rData, UINT8 retryCount,UINT64 filter);

			OGRE_MUTEX(mIdleMutex);
			RequestQueue mIdleRequestQueue; // Guarded by mIdleMutex
			bool mIdleThreadRunning; // Guarded by mIdleMutex
			CRequest* mIdleProcessed; // Guarded by mProcessMutex

			bool processIdleRequests();

		public:
			//// Notify workers about a new request.
			virtual void notifyWorkers();
		};

		class FD_Kernel_Export BackgroundQueue : public FD::Kernel::CReferenced
		{
		public:
			BackgroundQueue() {}
		public:
			/// </summary>
			/// 初始化这个BackgroundQueue
			/// </summary>
			/// <returns>None</returns>
			virtual void initialise() ; 			///PURE function
			/// </summary>
			/// 卸载这个BackgroundQueue
			/// </summary>
			/// <returns>None</returns>
			virtual void shutdown() ;         			///PURE function
			/// </summary>
			/// 获取BackgroundQueue所在的组
			/// </summary>
			/// <returns>组名</returns>
			virtual String getGroupName() const;			///PURE function
			/// </summary>
			/// 获取BackgroundQueue的名字，唯一标识
			/// </summary>
			/// <returns>BackgroundQueue的名字</returns>
			virtual String getName() const;			///PURE function
		};

		class LicenseDriver;
		class LicenseCensor;
		class FD_Kernel_Export BackgroundQueueManager : public FD::Kernel::CReferenced
		{
		public:
			BackgroundQueueManager(FD::Kernel::LicenseDriver* pLD = NULL);

			virtual ~BackgroundQueueManager();

		protected:
			static FD::Kernel::BackgroundQueueManager* msSingleton;

		public:
			static FD::Kernel::BackgroundQueueManager *getSingletonPtr();
			static FD::Kernel::BackgroundQueueManager &getSingleton();  

			/// </summary>
			/// 注册一个BackgroundQueue
			/// </summary>
			/// <returns>None</returns>
			void registerBackgroundQueue(FD::Kernel::BackgroundQueue *queue);
			/// </summary>
			/// 卸载一个BackgroundQueue
			/// </summary>
			/// <returns>None</returns>
			void unregisterBackgroundQueue(FD::Kernel::BackgroundQueue *queue);
			/// </summary>
			/// 通过名字获取BackgroundQueue
			/// </summary>
			/// <returns>BackgroundQueue实例</returns>
			FD::Kernel::BackgroundQueue   *getBackgroundQueue(const String &name) const;
			/// </summary>
			/// 获取已经存在的BackgroundQueue的所有组名
			/// </summary>
			/// <returns>已经存在的BackgroundQueue的所有组名</returns>
			FD::Kernel::StringVector		getRegisterBackgroundQueueNames() const;
			/// </summary>
			/// 获取已经存在的BackgroundQueue的所有名称
			/// </summary>
			/// <returns>已经存在的BackgroundQueue的所有名称</returns>
			FD::Kernel::StringVector		getRegisterBackgroundGroupNames() const;

			/// </summary>
			/// 清空BackgroundQueue
			/// </summary>
			/// <returns>None</returns>
			void clearBackgroundQueues();

			/// </summary>
			/// 初始化所有BackgroundQueue
			/// </summary>
			/// <returns>None</returns>
			void initialiseAllGroups();
			/// </summary>
			/// 初始化组名里得所有BackgroundQueue
			/// </summary>
			/// <returns>None</returns>
			void initialise( String groupName);
			/// </summary>
			/// 卸载所有BackgroundQueue
			/// </summary>
			/// <returns>None</returns>
			void shutdownAllGroups();
			/// </summary>
			/// 卸载组名里得所有BackgroundQueue
			/// </summary>
			/// <returns>None</returns>
			void shutdown( String groupName) ;
		private:
			typedef vector<FD::Kernel::BackgroundQueue *> BackgroundQueues;
		protected:
			BackgroundQueues  mWorkQueues;

			LicenseCensor* mpLicenseCensor;
		};
	}
}

#endif

